import { Body, Controller, Get, Post, Req, UseGuards, UsePipes } from '@nestjs/common';
import { AuthService } from './auth.service';
import { ZodValidationPipe } from '../../common/pipes/zod-validation.pipe';
import {
  LoginDto,
  RefreshTokenDto,
  loginSchema,
  refreshTokenSchema
} from './dto/auth.schema';
import { JwtAuthGuard } from './guards/jwt-auth.guard';
import { CurrentUser } from '../../common/decorators/current-user.decorator';
import { RoleService } from '../role/role.service';
import { MenuService } from '../menu/menu.service';
import { Request } from 'express';
import { Public } from '../../common/decorators/public.decorator';
import { RequiresPermissions } from '../../common/decorators/requires-permissions.decorator';
import { ApiOperation, ApiParam, ApiTags } from '@nestjs/swagger'

@ApiTags('Auth - 认证模块')
@Controller('auth')
export class AuthController {
  constructor(
    private readonly authService: AuthService,
    private readonly roleService: RoleService,
    private readonly menuService: MenuService,
  ) { }

  /**
   * 用户登录
   */
  @Post('login')
  @ApiOperation({ summary: '登录' })
  @Public() // 标记为公共接口，不需要认证
  @UsePipes(new ZodValidationPipe(loginSchema))
  @ApiParam({ name: 'username', description: '用户名' })
  @ApiParam({ name: 'password', description: '密码' })
  login(@Body() loginDto: LoginDto, @Req() req: Request) {
    return this.authService.login(loginDto, req);
  }



  /**
   * 刷新Token
   */
  @Post('refresh-token')
  @ApiOperation({ summary: '刷新token' })
  @Public() // 标记为公共接口，不需要认证
  @UsePipes(new ZodValidationPipe(refreshTokenSchema))
  refreshToken(@Body() refreshTokenDto: RefreshTokenDto) {
    return this.authService.refreshToken(refreshTokenDto);
  }

  /**
   * 获取当前登录用户信息
   */
  @Get('profile')
  @ApiOperation({ summary: '获取当前登录用户信息' })
  async getUserProfile(@CurrentUser() user: any) {
    // 获取用户角色
    const roles = await this.roleService.getRolesByUserId(user.userId);

    // 获取用户权限标识（直接从菜单获取，不查询sys_permission表）
    const roleIds = roles.map(role => role.roleId);
    const permissionKeys = await this.menuService.getUserPermissionKeysByRoleIds(roleIds);

    return {
      user: {
        userId: user.userId,
        userName: user.userName,
        nickName: user.nickName,
        email: user.email,
        deptId: user.deptId,
        avatar: user.avatar,
        roles: roles.map(role => ({
          roleId: role.roleId,
          roleName: role.roleName,
          roleKey: role.roleKey,
        })),
        permissions: permissionKeys.map(key => ({
          permissionKey: key,
        })),
      },
    };
  }

  /**
   * 获取当前登录用户的菜单权限标识
   * 直接从菜单获取权限标识，不查询sys_permission表
   */
  @Get('menu-permissions')
  @ApiOperation({ summary: '获取用户菜单权限标识' })
  async getUserMenuPermissions(@CurrentUser() user: any) {
    // 获取用户角色
    const roles = await this.roleService.getRolesByUserId(user.userId);
    const roleIds = roles.map(role => role.roleId);

    // 获取菜单权限标识
    const permissionKeys = await this.menuService.getUserPermissionKeysByRoleIds(roleIds);

    return {
      permissions: permissionKeys,
    };
  }

  /**
   * 获取当前登录用户的授权菜单按钮
   * 返回详细的菜单按钮信息
   */
  @Get('authorized-buttons')
  @ApiOperation({ summary: '获取用户授权的菜单按钮' })
  async getUserAuthorizedButtons(@CurrentUser() user: any) {
    // 获取用户角色
    const roles = await this.roleService.getRolesByUserId(user.userId);
    const roleIds = roles.map(role => role.roleId);

    // 获取授权的菜单按钮
    const authorizedButtons = await this.menuService.getAuthorizedMenuButtonsByRoleIds(roleIds);

    return {
      buttons: authorizedButtons,
    };
  }

  /**
   * 测试Token接口 - 需要认证但不需要权限
   */
  @Get('test-token')
  @ApiOperation({ summary: '测试Token接口' })
  async testToken(@Req() req: Request, @CurrentUser() user: any) {
    // 打印请求头信息和用户信息，帮助排查问题
    console.log('请求头：', req.headers);
    console.log('用户信息：', user);

    return {
      message: '认证成功',
      user: user
    };
  }

  /**
   * 测试带权限的接口
   */
  @Get('test-permission')
  @ApiOperation({ summary: '测试带权限的接口' })
  @RequiresPermissions('system:test:list')
  async testPermission(@CurrentUser() user: any) {
    return {
      message: '权限验证成功',
      user: user
    };
  }
}